package com.jchen.elasticsearch.dto;

import cn.hutool.core.util.StrUtil;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
import co.elastic.clients.elasticsearch._types.query_dsl.RangeQuery;
import co.elastic.clients.json.JsonData;
import lombok.Data;

/**
 * @Description
 * @Author jchen
 * @Date 2023/12/21 17:25
 */
@Data
public class SysUserEsQueryReqDto {
    private Integer startAge;
    private Integer endAge;
    private Double balance;
    private Boolean enabled;
    private String name;

    /**
     * 构建查询条件，都采用filter，索引采用的默认分词
     * @return Query
     */
    public Query buildQuery() {
        Query.Builder queryBuilder = new Query.Builder();
        BoolQuery.Builder boolQueryBuilder = new BoolQuery.Builder();


        String name = null == this.name ? null : this.name.replace("*", "").replace("?", "");
        if (StrUtil.isNotBlank(name)) {
            boolQueryBuilder.filter(QueryBuilders.wildcard().field("name.keyword").value("*" + name + "*").build()._toQuery());
        }

        // 流入时间查询
        if (null != this.startAge || null != this.startAge) {
            RangeQuery.Builder ageRangeQuery = QueryBuilders.range().field("age");
            if (null != this.startAge) {
                ageRangeQuery.gte(JsonData.of(this.startAge));
            }
            if (null != this.endAge) {
                ageRangeQuery.lt(JsonData.of(this.endAge));
            }
            boolQueryBuilder.filter(ageRangeQuery.build()._toQuery());
        }
        return queryBuilder.bool(boolQueryBuilder.build()).build();
    }
}
